package mail.util;

import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * A utility class that is used for sending mail
 * 
 * @author Jonas Lindmark
 */
public class Sender {
    private Session iSession = null;
    private Properties iProperties = null;
    private InternetAddress iSender = null;
    /**
     * Default sender instance
     */
    public Sender()
    {
        iProperties = new Properties();
        iSession = Session.getDefaultInstance(iProperties,null);
    }
    /**
     * Set sender
     * 
     * @param sender
     * @throws java.io.UnsupportedEncodingException 
     */
    public void setSender(String sender) throws java.io.UnsupportedEncodingException
    {
        iSender = new InternetAddress(sender,"");
    }
    /**
     * Send a mail
     * 
     * @param to
     * @param subject
     * @param body
     * @throws Exception 
     */
    public void sendMail(String to, String subject, String body) throws Exception
    {
        if (iSender == null)
        {
            throw new Exception("Set sender before attempting to send!");
        }
        Message msg = new MimeMessage(iSession);
        msg.setFrom(iSender);
        msg.addRecipient(Message.RecipientType.TO,new InternetAddress(to,""));
        msg.setSubject(subject);
        msg.setText(body);
        Transport.send(msg);
    }

}
